<template>
  <view class="dashboard-container page-container">
    <!-- 页面标题 -->
    <view class="dashboard-header card fade-in">
      <view class="header-left">
        <text class="title">仪表盘</text>
        <text class="subtitle"
          >欢迎回来，{{ userStore.getUserInfo().permissions[0] }}--{{
            userStore.getUserInfo().nickname
          }}</text
        >
      </view>
      <view class="header-right">
        <view class="date-box flex-center">
          <up-icon name="calendar" color="var(--primary-color)" size="22"></up-icon>
          <text class="date">{{ currentDate }}</text>
        </view>
        <view class="refresh-btn">
          <up-button
            type="primary"
            icon="reload"
            size="mini"
            @click="refreshData"
            :loading="loading"
          ></up-button>
        </view>
      </view>
    </view>

    <!-- 数据概览卡片 -->
    <view class="card-grid">
      <!-- 第一行 -->
      <view class="data-card user-card card-hover fade-in" style="animation-delay: 0.1s">
        <view class="card-icon user-icon">
          <up-icon name="account-fill" color="#ffffff" size="28"></up-icon>
        </view>
        <view class="card-content">
          <text class="card-title">本周用户</text>
          <view class="card-data">
            <up-count-to
              class="data-value"
              :startVal="0"
              :endVal="dashboardData.weekUserCount || 0"
              :duration="2000"
              :useEasing="false"
            ></up-count-to>
            <view class="data-trend" :class="userTrend.class">
              <text class="trend-value">{{ userTrend.value }}%</text>
              <text class="trend-icon">{{ userTrend.icon }}</text>
            </view>
          </view>
          <text class="card-compare"
            >上周: {{ dashboardData.lastWeekUserCount || 0 }}</text
          >
        </view>
      </view>

      <view class="data-card order-card card-hover fade-in" style="animation-delay: 0.2s">
        <view class="card-icon order-icon">
          <up-icon
            name="shopping-cart-fill"
            color="#ffffff"
            size="28"
          ></up-icon>
        </view>
        <view class="card-content">
          <text class="card-title">本周订单</text>
          <view class="card-data">
            <up-count-to
              class="data-value"
              :startVal="0"
              :endVal="dashboardData.weekOrderCount || 0 || 0"
              :duration="2000"
              :useEasing="false"
            ></up-count-to>
            <view class="data-trend" :class="orderTrend.class">
              <text class="trend-value">{{ orderTrend.value }}%</text>
              <text class="trend-icon">{{ orderTrend.icon }}</text>
            </view>
          </view>
          <text class="card-compare"
            >上周: {{ dashboardData.lastWeekOrderCount || 0 }}</text
          >
        </view>
      </view>

      <!-- 第二行 -->
      <view class="data-card money-card card-hover fade-in" style="animation-delay: 0.3s">
        <view class="card-icon money-icon">
          <up-icon name="rmb-circle-fill" color="#ffffff" size="28"></up-icon>
        </view>
        <view class="card-content">
          <text class="card-title">本周收入</text>
          <view class="card-data">
            <text class="data-value"
              >¥{{ formatMoney(dashboardData.weekOrderMoney) }}</text
            >
            <view class="data-trend" :class="moneyTrend.class">
              <text class="trend-value">{{ moneyTrend.value }}%</text>
              <text class="trend-icon">{{ moneyTrend.icon }}</text>
            </view>
          </view>
          <text class="card-compare"
            >上周: ¥{{ formatMoney(dashboardData.lastWeekOrderMoney) }}</text
          >
        </view>
      </view>

      <view class="data-card complaint-card card-hover fade-in" style="animation-delay: 0.4s">
        <view class="card-icon complaint-icon">
          <up-icon name="warning-fill" color="#ffffff" size="28"></up-icon>
        </view>
        <view class="card-content">
          <text class="card-title">本周投诉</text>
          <view class="card-data">
            <up-count-to
              class="data-value"
              :startVal="0"
              :endVal="dashboardData.weekComplaintCount || 0"
              :duration="2000"
              :useEasing="false"
            ></up-count-to>
            <view class="data-trend" :class="complaintTrend.class">
              <text class="trend-value">{{ complaintTrend.value }}%</text>
              <text class="trend-icon">{{ complaintTrend.icon }}</text>
            </view>
          </view>
          <text class="card-compare"
            >上周: {{ dashboardData.lastWeekComplaintCount || 0 }}</text
          >
        </view>
      </view>
    </view>

    <!-- 数据加载中或加载失败提示 -->
    <view v-if="loading" class="loading-container">
      <LoadingState type="dots" text="数据加载中"/>
    </view>

    <view v-if="error" class="error-container flex-center">
      <text class="error-message">{{ errorMessage }}</text>
      <up-button type="primary" size="mini" @click="refreshData"
        >重试</up-button
      >
    </view>

    <!-- 统计图表区域 -->
    <view class="chart-section card fade-in" style="animation-delay: 0.5s">
      <view class="section-header flex-between">
        <view class="section-title flex-start">
          <up-icon name="grid-fill" color="var(--primary-color)" size="24"></up-icon>
          <text class="ml-sm">数据统计</text>
        </view>
        <view class="section-tabs">
          <text class="tab active">本周</text>
        </view>
      </view>
      <view class="section-content">
        <view class="chart-wrapper">
          <view class="chart-title">销售金额趋势</view>
          <LEchart
            ref="moneyChartRef"
            id="moneyChart"
            class="chart-canvas"
          ></LEchart>
        </view>
        <view class="chart-wrapper">
          <view class="chart-title">用户数量分析</view>
          <LEchart
            ref="userChartRef"
            id="userChart"
            class="chart-canvas"
          ></LEchart>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import { onReady, onShow } from "@dcloudio/uni-app";
import { getDashboardData, getDashBoardChart } from "@/api/dashboard";
import LEchart from "@/components/l-echart/l-echart.vue";
import { useUserStore } from "@/stores/user";
import LoadingState from "@/components/LoadingState.vue";

const userStore = useUserStore();

const echarts = require("../../static/echarts.min");

// 仪表板数据
const dashboardData = ref({
  weekUserCount: 0,
  lastWeekUserCount: 0,
  weekOrderCount: 0,
  lastWeekOrderCount: 0,
  weekOrderMoney: 0,
  lastWeekOrderMoney: 0,
  weekComplaintCount: 0,
  lastWeekComplaintCount: 0,
});

const loading = ref(false);
const error = ref(false);
const errorMessage = ref("");

// 计算当前日期
const currentDate = computed(() => {
  const date = new Date();
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");

  const weekDays = ["日", "一", "二", "三", "四", "五", "六"];
  const weekDay = weekDays[date.getDay()];

  return `${year}-${month}-${day} 星期${weekDay}`;
});

// 计算用户增长趋势
const userTrend = computed(() => {
  if (!dashboardData.value.lastWeekUserCount)
    return { value: 0, icon: "-", class: "" };

  const diff =
    dashboardData.value.weekUserCount - dashboardData.value.lastWeekUserCount;
  const percentage = Math.round(
    (diff / dashboardData.value.lastWeekUserCount) * 100
  );

  return {
    value: Math.abs(percentage),
    icon: percentage >= 0 ? "▲" : "▼",
    class: percentage >= 0 ? "trend-up" : "trend-down",
  };
});

// 计算订单增长趋势
const orderTrend = computed(() => {
  if (!dashboardData.value.lastWeekOrderCount)
    return { value: 0, icon: "-", class: "" };

  const diff =
    dashboardData.value.weekOrderCount - dashboardData.value.lastWeekOrderCount;
  const percentage = Math.round(
    (diff / dashboardData.value.lastWeekOrderCount) * 100
  );

  return {
    value: Math.abs(percentage),
    icon: percentage >= 0 ? "▲" : "▼",
    class: percentage >= 0 ? "trend-up" : "trend-down",
  };
});

// 计算收入增长趋势
const moneyTrend = computed(() => {
  if (!dashboardData.value.lastWeekOrderMoney)
    return { value: 0, icon: "-", class: "" };

  const diff =
    dashboardData.value.weekOrderMoney - dashboardData.value.lastWeekOrderMoney;
  const percentage = Math.round(
    (diff / dashboardData.value.lastWeekOrderMoney) * 100
  );

  return {
    value: Math.abs(percentage),
    icon: percentage >= 0 ? "▲" : "▼",
    class: percentage >= 0 ? "trend-up" : "trend-down",
  };
});

// 计算投诉增长趋势
const complaintTrend = computed(() => {
  if (!dashboardData.value.lastWeekComplaintCount)
    return { value: 0, icon: "-", class: "" };

  const diff =
    dashboardData.value.weekComplaintCount -
    dashboardData.value.lastWeekComplaintCount;
  const percentage = Math.round(
    (diff / dashboardData.value.lastWeekComplaintCount) * 100
  );

  // 投诉减少是好事，所以趋势显示相反
  return {
    value: Math.abs(percentage),
    icon: percentage >= 0 ? "▲" : "▼",
    class: percentage >= 0 ? "trend-down" : "trend-up",
  };
});

// 格式化金额
const formatMoney = (value) => {
  if (!value) return "0.00";
  return (value / 100).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// 获取仪表板数据
const fetchDashboardData = async () => {
  loading.value = true;
  error.value = false;

  try {
    const res = await getDashboardData();
    if (res.success && res.data) {
      dashboardData.value = res.data;
    } else {
      error.value = true;
      errorMessage.value = res.message || "获取数据失败";
    }
  } catch (err) {
    console.error("获取仪表板数据失败", err);
    error.value = true;
    errorMessage.value = "网络错误，请稍后重试";

    // 如果是登录过期等问题，不显示错误信息，让请求拦截器处理重定向
    if (
      err.status === 401 ||
      (err.message && err.message.includes("登录已过期"))
    ) {
      error.value = false;
    }
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const refreshData = () => {
  fetchDashboardData();
};

const moneyChartRef = ref(null);
const userChartRef = ref(null);

async function initCharts() {
  const res = await getDashBoardChart();
  if (!res.success) {
    return ElMessage.error(res.message);
  }

  // 通用图表配置
  const commonOptions = {
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#eee",
      borderWidth: 1,
      textStyle: {
        color: "#333",
      },
      axisPointer: {
        type: "shadow",
        shadowStyle: {
          color: "rgba(0, 0, 0, 0.03)",
        },
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "4%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
      axisLine: {
        lineStyle: {
          color: "#ddd",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#666",
      },
    },
    yAxis: {
      type: "value",
      splitLine: {
        lineStyle: {
          color: "#eee",
          type: "dashed",
        },
      },
      axisLabel: {
        color: "#666",
      },
    },
  };
  const moneyOptions = {
    ...commonOptions,
    title: {
      left: "center",
      top: "10px",
      textStyle: {
        color: "#333",
        fontSize: 16,
        fontWeight: "normal",
      },
    },
    series: [
      {
        name: "成交额",
        type: "line",
        data: res.data.weekOrderMoneyList,
        smooth: true,
        symbol: "circle",
        symbolSize: 8,
        itemStyle: {
          color: "#409EFF",
        },
        lineStyle: {
          width: 3,
          color: "#409EFF",
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: "rgba(64, 158, 255, 0.2)",
            },
            {
              offset: 1,
              color: "rgba(64, 158, 255, 0)",
            },
          ]),
        },
      },
    ],
  };
  // 成交额趋势图
  // const moneyChart = echarts.init(moneyChartRef.value);
  // moneyChart.setOption(moneyOptions);
  moneyChartRef.value.init(echarts, (chart) => {
    chart.setOption(moneyOptions);
  });
  // 用户数分析图
  // const userChart = echarts.init(document.getElementById("userChart"));
  const userOptions = {
    ...commonOptions,
    title: {
      left: "center",
      top: "10px",
      textStyle: {
        color: "#333",
        fontSize: 16,
        fontWeight: "normal",
      },
    },
    series: [
      {
        name: "用户数",
        type: "bar",
        data: res.data.weekUserCountList,
        barWidth: "40%",
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: "#83bff6",
            },
            {
              offset: 0.5,
              color: "#409EFF",
            },
            {
              offset: 1,
              color: "#2e88ff",
            },
          ]),
          borderRadius: [4, 4, 0, 0],
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: "#66b1ff",
              },
              {
                offset: 0.7,
                color: "#409EFF",
              },
              {
                offset: 1,
                color: "#3a8ee6",
              },
            ]),
          },
        },
      },
    ],
  };
  // const userChart = echarts.init(userChartRef.value);
  // userChart.setOption(userOptions);
  userChartRef.value.init(echarts, (chart) => {
    chart.setOption(userOptions);
  });
}

onShow(() => {
  // 每次显示页面时刷新数据
  fetchDashboardData();
});

onReady(() => {
  uni.setNavigationBarTitle({
    title: "首页",
  });
});

onMounted(() => {
  // 初始化图表
  initCharts();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  min-height: 100vh;

  .dashboard-header {
    margin-bottom: 20rpx;
    padding: 24rpx 30rpx;

    .header-left {
      .title {
        font-size: 36rpx;
        font-weight: bold;
        color: var(--text-primary);
        display: block;
        margin-bottom: 6rpx;
      }

      .subtitle {
        font-size: 24rpx;
        color: var(--text-secondary);
      }
    }

    .header-right {
      display: flex;
      align-items: center;

      .date-box {
        margin-right: 15rpx;
        background-color: var(--primary-bg);
        padding: 10rpx 20rpx;
        border-radius: 30rpx;
        box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.03);

        .date {
          font-size: 22rpx;
          color: var(--text-primary);
          margin-left: 8rpx;
          font-weight: 500;
        }
      }

      .refresh-btn {
        margin-left: 8rpx;

        :deep(.u-button--mini) {
          min-width: auto;
          width: 64rpx;
          height: 64rpx;
          border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;

          .u-button__text {
            margin: 0;
          }
        }
      }
    }
  }

  .card-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 20rpx;
    margin-bottom: 24rpx;

    .data-card {
      background-color: var(--bg-card);
      border-radius: var(--border-radius-lg);
      padding: 24rpx;
      box-shadow: var(--box-shadow-light);
      display: flex;
      transition: all 0.3s ease;

      &:active {
        transform: translateY(-2rpx);
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
      }

      .card-icon {
        width: 80rpx;
        height: 80rpx;
        border-radius: var(--border-radius-lg);
  display: flex;
        align-items: center;
  justify-content: center;
        margin-right: 16rpx;
        box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
      }

      .card-content {
        flex: 1;

        .card-title {
          font-size: 24rpx;
          color: var(--text-secondary);
          margin-bottom: 10rpx;
        }

        .card-data {
          display: flex;
          align-items: baseline;
          margin-bottom: 10rpx;

          .data-value {
            font-size: 36rpx;
            font-weight: bold;
            color: var(--text-primary);
            margin-right: 10rpx;
          }

          .data-trend {
            font-size: 20rpx;
            display: flex;
            align-items: center;
            border-radius: 10rpx;
            padding: 2rpx 8rpx;

            &.trend-up {
              color: var(--error-color);
              background-color: rgba(245, 34, 45, 0.1);
            }

            &.trend-down {
              color: var(--success-color);
              background-color: rgba(82, 196, 26, 0.1);
            }

            .trend-value {
              margin-right: 2rpx;
            }
          }
        }

        .card-compare {
          font-size: 20rpx;
          color: var(--text-tertiary);
        }
      }
    }
  }

  .loading-container,
  .error-container {
    height: 150rpx;
    margin: 20rpx 0;

    .error-message {
      color: var(--error-color);
      margin-bottom: 16rpx;
      font-size: 24rpx;
    }
  }

  .chart-section {
    margin-top: 20rpx;
    padding: 24rpx;

    .section-header {
      margin-bottom: 24rpx;
      padding-bottom: 20rpx;
      border-bottom: 1px solid var(--border-color-split);

      .section-title {
        font-size: 30rpx;
        font-weight: bold;
        color: var(--text-primary);
      }

      .section-tabs {
        display: flex;

        .tab {
          padding: 6rpx 20rpx;
          font-size: 22rpx;
          color: var(--text-secondary);
          margin-left: 8rpx;
          border-radius: var(--border-radius-base);
          transition: all 0.3s;

          &.active {
            background-color: var(--primary-bg);
            color: var(--primary-color);
            font-weight: 500;
          }

          &:active {
            opacity: 0.8;
          }
        }
      }
    }

    .section-content {
      display: flex;
      flex-direction: column;

      .chart-wrapper {
        flex: 1;
        margin-bottom: 20rpx;
        padding: 20rpx;
        background-color: #f8f9fc;
        border-radius: var(--border-radius-lg);

        .chart-title {
          font-size: 26rpx;
          font-weight: 500;
          color: var(--text-primary);
          margin-bottom: 16rpx;
          text-align: center;
        }
      }
    }
  }
}

.chart-canvas {
  width: 100%;
  height: 320rpx;
}

// 大屏幕适配
@media screen and (min-width: 768px) {
  .dashboard-container {
    padding: 30rpx;

    .dashboard-header {
      padding: 30rpx 36rpx;
      margin-bottom: 30rpx;

      .header-left {
.title {
          font-size: 40rpx;
        }

        .subtitle {
          font-size: 26rpx;
        }
      }
    }

    .card-grid {
      grid-template-columns: repeat(4, 1fr);
      grid-gap: 24rpx;
      margin-bottom: 30rpx;

      .data-card {
        padding: 28rpx;

        .card-icon {
          width: 88rpx;
          height: 88rpx;
        }

        .card-content {
          .card-title {
            font-size: 26rpx;
          }

          .card-data {
            .data-value {
              font-size: 40rpx;
            }

            .data-trend {
              font-size: 22rpx;
            }
          }

          .card-compare {
            font-size: 22rpx;
          }
        }
      }
    }

    .chart-section {
      padding: 36rpx;
      margin-top: 30rpx;

      .section-content {
        flex-direction: row;
        gap: 24rpx;

        .chart-wrapper {
          margin-bottom: 0;
          padding: 24rpx;

          .chart-title {
            font-size: 28rpx;
          }

          .chart-canvas {
            height: 380rpx;
          }
        }
      }
    }
  }
}

.user-icon {
  background: linear-gradient(135deg, #36CCCB, #188FFF);
}

.order-icon {
  background: linear-gradient(135deg, #52C873, #009900);
}

.money-icon {
  background: linear-gradient(135deg, #FFB545, #FF8C00);
}

.complaint-icon {
  background: linear-gradient(135deg, #FF6B78, #E74C3C);
}
</style>
